<?php
include_once('./config/config.php');

// 判断有没有表单提交
if ($_POST) {
  // 接收全部参数
  $params = $_POST;

  if ($_POST['action'] == 'val') {
    $val = $_POST['val'];
    $res = findOne("select * from admin where username = '$val'");
    if ($res) {
      error("该管理员已存在");
    } else {
      success("名称可以使用");
    }
  }

  if ($params['password'] != $params['repass']) {
    ShowMsg('密码不一致，请重试');
    exit;
  }
  // 设置密码盐
  $salt = build_ranstr();
  if (!$salt) {
    ShowMsg('密码盐缺失');
    exit;
  }
  $password = md5($params['password'].$salt);
  // 调用上传函数
  $avatar = upload('avatar');
  // 重新封装数据
  $data = [
    'username' => $params['username'],
    'password' => $password,
    'avatar' => $avatar['data'],
    'salt' => $salt,
  ];
  $res = insert('admin', $data);
  if ($res) {
    ShowMsg("新增管理员成功");
  } else {
    ShowMsg("SQL语句执行失败：" . mysqli_error($conn));
  }
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
  <!-- 引入 -->
  <?php include_once('./common/meta.php') ?>
</head>

<style>
  .avatar_lab {
    width: 200px;
  }

  .avatar_img {
    width: 200px;
  }
</style>

<body>
  <!--<![endif]-->

  <!-- 引入头部导航 -->
  <?php include_once('./common/navbar.php') ?>

  <!-- 引入侧边菜单栏 -->
  <?php include_once('./common/sidebar.php') ?>

  <div class="content">
    <div class="header">
      <h1 class="page-title">添加管理员</h1>
    </div>
    <ul class="breadcrumb">
      <li><a href="index.php">Home</a> <span class="divider">/</span></li>
      <li class="active">Index</li>
    </ul>

    <div class="container-fluid">
      <div class="row-fluid">
        <div class="btn-toolbar">
          <button class="btn btn-primary" onClick="location='adminList.php'"><i class="icon-list"></i>  返回列表</button>
          <div class="btn-group">
          </div>
        </div>

        <div class="well">
          <div id="myTabContent" class="tab-content">
            <div class="tab-pane active in" id="home">
              <form method="POST" enctype="multipart/form-data">

                <!-- 用户名 -->
                <label>用户名</label>
                <input type="text" class="input-xxlarge" name="username" placeholder="请输入用户名" required>
                <span id="username"></span>
                <!-- 密码 -->
                <label>密码</label>
                <input type="password" class="input-xxlarge" name="password" placeholder="请输入密码" required>

                <!-- 确认密码 -->
                <label>确认密码</label>
                <input type="password" class="input-xxlarge" name="repass" placeholder="请确认密码" required>

                <!-- 头像 -->
                <label>头像</label>
                <input type="file" name="avatar" id="avatar" hidden>
                <label for="avatar" class="avatar_lab">
                  <img src="./static/images/upload.png" alt="" id="avatar_img">
                </label>

                <button class="btn btn-primary" type="submit" value="提交">提交</button>
              </form>
            </div>
          </div>
        </div>

        <!-- 引入底部 -->
        <?php include_once('./common/footer.php') ?>

      </div>
    </div>
  </div>

</body>

</html>
<!-- 引用公共js文件 -->
<?php include_once('./common/script.php') ?>
<script>

  $("input[name='username']").change(function() {
    let val = $(this).val()
    $.ajax({
      type: 'post',
      url: 'addAdmin.php',
      data: {
        val,
        action: 'val'
      },
      dataType: 'json',
      success: function(res) {
        if (res.code == 1) {
          $("#username").text(res.msg).css({"color": "blue"})
        } else {
          $("#username").text(res.msg).css({"color": "red"})
        }
      },
      error: function(err) {
        console.log(err)
      }
    })
  })

  // 图片预览函数
  function GetObjectURL(file) {
    // createObjectURL  给一个文件对象 可以提取出一个url本地地址出来
    var url = null;

    //判断是否为IE浏览器还是google还是其他浏览器
    if (window.createObjectURL != undefined) {
      url = window.createObjectURL(file)
    } else if (window.URL != undefined) {
      url = window.URL.createObjectURL(file)
    } else if (window.webkitURL != undefined) {
      url = window.webkitURL.createObjectURL(file)
    }

    return url
  }

  $('#avatar').change(function() {
    // 获取选中的文件
    let file = $(this)[0].files[0] ? $(this)[0].files[0] : {}
    // 获取该文件地址
    let src = GetObjectURL(file)
    // console.log(src)
    $('#avatar_img').attr('src', src)
  })
</script>